package com.wu.kafka;

import org.apache.kafka.clients.producer.Partitioner;
import org.apache.kafka.common.Cluster;
import org.apache.kafka.common.PartitionInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;

/**
 * @author wufei
 * @date 2018/3/22/022 14:41
 */
public class MyPartition implements Partitioner {
    private static final Logger logger = LoggerFactory.getLogger(MyPartition.class);
    @Override
    public int partition(String topic, Object key, byte[] bytes, Object o1, byte[] bytes1, Cluster cluster) {
        List<PartitionInfo> partitionInfos = cluster.partitionsForTopic(topic);
        //这里的numpart 是 partition num 不是partition count。如果有partition挂了。总数不会变
        int numPart = partitionInfos.size();
        int hashCode = key.hashCode();


        logger.info("partition count :"+numPart);
        return Math.abs(hashCode)%numPart;
    }

    @Override
    public void close() {

    }

    @Override
    public void configure(Map<String, ?> map) {

    }
}
